package org.theSeed.springDynamicDatasource.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.theSeed.springDatasouceProp.pojo.SeedBaseDataSourceHolder;
import org.theSeed.springDynamicDatasource.contract.impl.DynamicDataSource;
import org.theSeed.springDynamicDatasource.utils.DynamicDataSourceUtil;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * 数据源注入到动态数据源中
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "seed-data-source-prop",name = "seed-spring-data-source-type",havingValue = "dynamic")
@AutoConfigureBefore({DataSourceAutoConfiguration.class})
public class SeedDynamicDataSourceConfig {
    @Autowired
    private SeedBaseDataSourceHolder seedBaseDataSourceHolder;

    @Bean
    @Primary
    public DataSource dataSource(){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(new HashMap<>(seedBaseDataSourceHolder.getDataSourceMap()));
        DynamicDataSourceUtil.setDefaultDb(seedBaseDataSourceHolder.getSeedDataSourceProp().getPrimary());
        log.info("动态数据源初始化成功,默认数据源为{}",seedBaseDataSourceHolder.getSeedDataSourceProp().getPrimary());
        return dynamicDataSource;
    }
}
